#include "Acsvr.h"

#define _CHECK_VAL_RET_(stmt,ret, errmsg) do{\
    if(stmt){\
        std::cout<<errmsg<<std::endl;\
    	return ret;\
	}\
}while(0);

Acsvr::Acsvr(Conf& conf)
:listenPort_(conf.listenPort)
,svrIp_(conf.svrIp)
,svrPort_(conf.svrPort) 
{
}

Acsvr::~Acsvr(){
} 

int Acsvr::startUp(){
	std::cout<<"acsvr startup"<<std::endl;
	    
	_CHECK_VAL_RET_( 0 != connectToSvr(),-1,"connect to svr fail");
	_CHECK_VAL_RET_( 0 != openListenPort(),-1,"open listen port fail");
	_CHECK_VAL_RET_( 0 != run(),-1,"run fail");

	return 0;
}
	
int Acsvr::onClientConnection(int fd){
    std::cout<<"connection is connected ,conId :"<<fd<<std::endl;
    //todo :accept
    //return true == conMap_.insert(std::make_pair(fd,1)) ? 0 : -1;
    conMap_.insert(std::make_pair(fd,1));
    return 0;
} 

int Acsvr::onClientDisconnection(int fd){
    std::cout<<"connection is disconnected ,conId :"<<fd<<std::endl;
    //todo:close
	conMap_.erase(fd);
	return 0;
}

int Acsvr::onRecvClientMsg(int fd,const std::string& req)const{
	std::cout<<"onRecvClientMsg,msg :"<< req<<std::endl;
	if(isFdExist(fd)){
		return sendMsgToSvr(fd,req);
	}else{
		std::cout<<"onRecvCientMsg:unexist fd: "<<fd<<std::endl;
		return -1;
	}
} 
	
int Acsvr::onRecvServerMsg(int fd,const std::string& rsp)const {
	std::cout<<"onRecvServerMsg,msg :"<< rsp<<std::endl;
	if(isFdExist(fd)){
		return sendMsgTocli(fd,req);
	}else{
		std::cout<<"onRecvServerMsg:unexist fd: "<<fd<<std::endl;
		return -1;
	}
}
    
int Acsvr::connectToSvr(){
    std::cout<<"connect to svr, ip: "<<svrIp_<< " port: "<<svrPort_<<std::endl;
    //todo connect
	return 0;
} 
    
int Acsvr::openListenPort(){
    std::cout<<"openListenPort , port: "<<listenPort_<<std::endl;
	//todo listen
	return 0;
} 

int Acsvr::run(){
  	std::cout<<"run "<< std::endl;
	//todo Reactor  As Test inside the prosess
	return 0;
}
	
bool Acsvr::isFdExist(int fd) const{
	auto it = conMap_.find(fd);
	return it!= conMap_.end() ? true : false;
}

int Acsvr::sendMsgToSvr(int fd, const std::string& msg) const{
	std::cout<<"sendMsgToServer  fd:"<<fd<<" msg: "<<msg<<std::endl;
    //todo write to svr
	return 0;
}	

int Acsvr::sendMsgTocli(int fd, const std::string& msg) const{
	std::cout<<"sendMsgToclient  fd:"<<fd<<" msg: "<<msg<<std::endl;
    //todo write to cli
	return 0;
}
    
